import axios from 'axios'
import qs from 'qs'
import md5 from 'md5'

axios.interceptors.request.use((conf) => {
  conf.auth = {
    username: 'linqinghu',
    password: '123456'
  };
  return conf
}, (error) => {
  //new Vue({}).$message.error('请求失败');
  return Promise.reject(error)
});
axios.interceptors.response.use((res) => {
  if (res.data.code === 0) {
    alert(res.data.msg);
    //return res.data
  } else if (res.data.code == 1) {
    return res.data
  } else if (res.data.code == 2) {

  } else if (res.data.code == 3) {

  } else if (res.data.code == 4) {

  } else if (res.status == 200) {
    return res.data;
  } else {

  }
  return Promise.reject(res);
}, (error) => {
  //new Vue({}).$message.error('响应失败');
  return Promise.reject(error)
});

export default {
  get: (url, params) => {
    return axiosRequestParams(url, 'get', params, 10000);
  },
  post: (url, params) => {
    return axiosRequestParams(url, 'post', params, 15000);
  },
  uploadForm: (url, params, formData) => {
    // 处理提交评论的个自定义方法
    return axiosRequestParams(url, 'post', params, 0, formData);
  }
};

function axiosRequestParams(url, method, paramsOrData, timeout, formData) {

  let params = {};
  let data = {};
  paramsOrData = paramsOrData || {};

  //paramsOrData.accessUserId = window.sessionStorage.getItem('YSUserId');

  if (method === 'get' || method === 'delete' || method === 'head') {
    params = paramsOrData;
    data = {};
  } else {
    params = {};
    data = qs.stringify(paramsOrData);
  }

  // 有formData 走这个；
  if (formData != null) {
    for (let attr in paramsOrData) {
      formData.append(attr, paramsOrData[attr]);
    }
  }
  // let uid = window.localStorage.getItem('uid') || 0;
  // let token = window.localStorage.getItem('token') || 0;
  // let time = new Date().getTime();
  // url += `?uid=${uid}&time=${time}&secret=${md5('71clouddangjiang' + token + time + uid)}`;
  return axiosRequest({
    method: method,
    url: url,
    params: params,
    data: formData ? formData : data,
    timeout: 10000
  })
}

function axiosRequest(conf) {
  return axios({
    method: conf.method || 'get',
    url: conf.url,
    params: conf.params || {},
    data: conf.data,
    timeout: conf.timeout || 10000
  })
}

